package com.androidsocketd;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.Guideline;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.androidsocketd.bean.MachineNumber;
import com.androidsocketd.dao.MachineNumDao;
import com.androidsocketd.productdaobase.ProductDatabase;
import com.androidsocketd.recycler.NormalRecyclerViewAdapter;
import com.androidsocketd.util.AppExecutors;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MachineActivity extends AppCompatActivity {

    MachineNumDao machineNumDao;
    AppExecutors executors;
    List<MachineNumber> machineNumberList = new ArrayList<>();

    @BindView(R.id.addText)
    EditText addText;
    @BindView(R.id.add)
    Button add;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    NormalRecyclerViewAdapter normalRecyclerViewAdapter;
    @BindView(R.id.showRomm)
    Button showRomm;
    @BindView(R.id.spinner)
    Spinner spinner;
    @BindView(R.id.guideline)
    Guideline guideline;
    @BindView(R.id.selectShow)
    Button selectShow;
    private Handler handler;
    ArrayAdapter<String> spinnerAdapter;
    List<String> spinnerDate = new ArrayList<>();

    class Mhandler extends Handler {

        // 通过复写handlerMessage() 从而确定更新UI的操作
        @Override
        public void handleMessage(Message msg) {
            // 根据不同线程发送过来的消息，执行不同的UI操作
            // 根据 Message对象的what属性 标识不同的消息
            switch (msg.what) {
                case 1:
                    spinnerAdapter.clear();
                    for (MachineNumber machine : machineNumberList) {
                        spinnerAdapter.add(machine.getMachineName());
                    }
//                    spinnerAdapter.addAll(spinnerDate);

                    normalRecyclerViewAdapter.notifyChange(machineNumberList);
                    break;
                case 2:
                    Toast.makeText(getApplicationContext(), "已存在", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_machine);
        ButterKnife.bind(this);
        initView();

        machineNumDao = ProductDatabase
                .getInstance(MachineActivity.this)
                .getMachineNumDao();
        executors = new AppExecutors();
        handler = new Mhandler();

        recyclerView.setLayoutManager(new LinearLayoutManager(this));//这里用线性显示 类似于listview
//        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));//这里用线性宫格显示 类似于grid view
//        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, OrientationHelper.VERTICAL));//这里用线性宫格显示 类似于瀑布流

        normalRecyclerViewAdapter = new NormalRecyclerViewAdapter(this, machineNumberList);
        recyclerView.setAdapter(normalRecyclerViewAdapter);
        normalRecyclerViewAdapter.setOnItemClickListener(new NormalRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, final int position) {
                executors.getDiskIO().execute(new Runnable() {
                    @Override
                    public void run() {
                        try {

                            machineNumDao.deleteOne(machineNumberList.get(position).getMachineName());
                            for (MachineNumber machineNumber : machineNumberList) {
                                if (machineNumber.getMachineName().equals(machineNumberList.get(position).getMachineName())) {
                                    machineNumberList.remove(machineNumber);
                                }
                            }

                            Message msg = Message.obtain();
                            msg.what = 1; //消息的标识
                            handler.sendMessage(msg);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
//                handler.postAtTime(new Runnable() {
//                    @Override
//                    public void run() {
//                        normalRecyclerViewAdapter.notifyChange(machineNumberList);
//                    }
//                }, 3000);
            }
        });

        executors.getDiskIO().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    machineNumberList = machineNumDao.getAllMachine();
                    Message msg = Message.obtain();
                    msg.what = 1; //消息的标识
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });


//        handler.postAtTime(new Runnable() {
//            @Override
//            public void run() {
//                normalRecyclerViewAdapter.notifyChange(machineNumberList);
//            }
//        }, 2000);
    }

    private void initView() {

        spinnerDate.clear();
        spinnerAdapter = new ArrayAdapter<String>(MachineActivity.this, android.R.layout.simple_spinner_item,
                spinnerDate);
        spinner.setAdapter(spinnerAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MachineActivity.this, "您选择的是：" + spinnerDate.get(position), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


    }

    @OnClick(R.id.add)
    public void setAddText() {
        final String addStr = addText.getText().toString();
        if (addText.getText() == null || TextUtils.isEmpty(addStr)) {
            Toast.makeText(MachineActivity.this, "数据不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            final MachineNumber machineNumber = new MachineNumber();
            machineNumber.setMachineName(addStr);

            executors.getDiskIO().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        MachineNumber machineNumber1 = machineNumDao.getMachineOne(addStr);
                        if (machineNumber1 != null) {
                            Message msg = Message.obtain();
                            msg.what = 2; //消息的标识
                            handler.sendMessage(msg);
                            return;
                        }

                        machineNumDao.insert(machineNumber);
                        machineNumberList.add(machineNumber);
                        Message msg = Message.obtain();
                        msg.what = 1; //消息的标识
                        handler.sendMessage(msg);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }

//        handler.postAtTime(new Runnable() {
//            @Override
//            public void run() {
//                normalRecyclerViewAdapter.notifyChange(machineNumberList);
//            }
//
//        }, 1000);


    }

    @OnClick(R.id.selectShow)
    public void showSpinner(){
        String showSpinnerStr =  spinner.getSelectedItem().toString();
        Toast.makeText(MachineActivity.this,showSpinnerStr,Toast.LENGTH_SHORT).show();
        
    }

    @OnClick(R.id.showRomm)
    public void showRoom() {
        executors.getDiskIO().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    machineNumberList = machineNumDao.getAllMachine();
                    Message msg = Message.obtain();
                    msg.what = 1; //消息的标识
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
//        handler.postAtTime(new Runnable() {
//            @Override
//            public void run() {
//                normalRecyclerViewAdapter.notifyChange(machineNumberList);
//            }
//        }, 1000);
    }

}
